<?php
namespace cubox\provider\webpack;

use cubox\Webpack;

class Html extends File{
 
    private function trimPath($value){
        $value = str_replace("'",'',$value); //去除 '
        $value = str_replace('"','',$value); //去除 "
        return trim($value);
    }

    public function plugImport($name,$path,$cache=false){
        $appList = array_keys(\cubox\Cubox::getAppList());
        $plugPath = substr($path,1);
        $jsContent =  'var  '.$name.' = { ';
        
        foreach($appList as $app){
            $filePath = \cubox\File::realPath($plugPath,ROOT.DS.APP.DS.$app.DS.'template'.DS.'plug');
                
            if (file_exists($filePath)){
                if(!Webpack::inFileList($this->name,$filePath) && $cache == false){
                    $obj = Webpack::fileDriver($this->name,$filePath,$this->webpackUrl,['name'=>$name.'_'.$app]);
                    $obj ->import =  true;
                    $obj -> pack();
                }
                 
                $jsContent .= $app.':'.$this->getFunctionName($filePath).'(),';
            }

        }
            
        $jsContent .= '}';
        
        return $jsContent;

    }
    
    public function jsImport($content,$cache=false){
        
        $regs = array();
        $list = array();
        $regs[]= '/^import[\s]([\S ]*?)[\s]from[\s]+([\S]*?);/U';
        $regs[]= '/\n+\s*import[\s]([\S ]*?)[\s]from[\s]+([\S]*?);/U';

        foreach($regs as $re){
            preg_match_all ($re, $content, $match);
            

            if (isset($match[0]) && !empty($match[0])){

                foreach ($match[0] as $k=>$v){

                    
                    $list[] = array(
                        'input' => $v,
                        'name'   => trim($match[1][$k]),
                        'value'  => $this->trimPath($match[2][$k]),
                    );
                }

            }
        }        

        foreach($list as $val){
            //判断路径是否包涵#号
            if(strpos($val['value'],'#') ===0){
                $content =  str_replace( $val['input'],$this->plugImport($val['name'],$val['value']),$content,$cache);
            }else{
                $path =  \cubox\File::cleanPath(\cubox\File::realPath($val['value'],pathInfo($this->file,PATHINFO_DIRNAME)));
                 
                if (file_exists($path)){

                    if(!Webpack::inFileList($this->name,$path) && $cache==false){
                        $obj = Webpack::fileDriver($this->name,$path,$this->webpackUrl,$val);
                        $obj -> import = true;
                        $obj -> pack();
                    }

                    $content =  str_replace( $val['input'],'var '.$val['name'].'= '.$this->getFunctionName($path).'();',$content);
                }else{
                    
                    $content =  str_replace( $val['input'],'var '.$val['name'].'= undefined; console.error("webpack no find '.(CUBOX_DEBUG?$path:$val['value']).'");',$content);
                }
            }
        }

        $regs = array();
        $list = array();
        // 无 name的js文件 
        $regs[] = '/^import[\s]+["\']{1}([^"\']+.js)["\']{1}[^"\';]*;/i';
        $regs[] = '/\n+\s*import[\s]+["\']{1}([^"\']+.js)["\']{1}[^"\';]*;/i';
        foreach($regs as $re){
            preg_match_all ($re, $content, $match);
         
            if (isset($match[0]) && !empty($match[0])){
    
                foreach ($match[0] as $k=>$v){
                    $list[] = array(
                        'input' => $v,
                        'value'  => $this->trimPath($match[1][$k]),
                    );
                }
            }
        }
       
        foreach($list as $val){
            $path =  \cubox\File::cleanPath(\cubox\File::realPath($val['value'],pathInfo($this->file,PATHINFO_DIRNAME)));
            if (file_exists($path)){

                if(!Webpack::inFileList($this->name,$path) && $cache==false){
                    $obj = Webpack::fileDriver($this->name,$path,$this->webpackUrl,$val);
                    $obj ->useExport =  true;
                    $obj ->import = false;
                    $obj -> pack();
                }
                $content =  str_replace( $val['input'],'',$content);
            }else{
                $content =  str_replace( $val['input'],'console.error("webpack no find '.(CUBOX_DEBUG?$path:$val['value']).'");',$content);
            }
        }
        
        return $content;
    }

    public function cssImport($content,$cache =  false){

        $regs = [];
        
        //CSS里面的连接
        $regs[]= '/@import[\s]+["\']{1}([^"\']+.css)["\']{1}[^"\';]*;/i';
        
        //JS的连接
        $regs[]= '/^import[\s]+["\']{1}([^"\']+.css)["\']{1}[^"\';]*;/i';
        $regs[]= '/\n+\s*import[\s]+["\']{1}([^"\']+.css)["\']{1}[^"\';]*;/i';

        foreach($regs  as $re){
            preg_match_all ($re, $content, $match);
            //print_r($match);
            $input = $match[0]; 
             
            if (isset($match[1]) && !empty($match[1])){
                foreach($match[1] as $key => $url){
                    
                    $url = $this->trimPath($url);
                    if ($this->localeUrl($url)){
                        $path = \cubox\File::realPath($url,pathInfo($this->file,PATHINFO_DIRNAME ));
                        if (file_exists($path) && pathInfo($path,PATHINFO_EXTENSION )=="css" && $cache==false){
                            if(!Webpack::inFileList($this->name,$path)){
                                $obj =  Webpack::fileDriver($this->name,$path,$this->webpackUrl);
                                $obj -> pack();
                            }
                        }
                    }else{
                        Webpack::addBeforeCss($this->name,$input[$key]);
                    }

                    $content =  str_replace( $input[$key],'',$content);
                }
            }
        }
        
        
        return $content;        
    }

    protected function getContent(){

        if (isset(self::$fileContent[$this->file])){
            return self::$fileContent[$this->file];
        }

        $content = '';
        if (file_exists($this->file)){
            $content =  file_get_contents($this->file);
        }

        self::$fileContent[$this->file] = $content;
        return $content;
    }

    /**
     * 判断是否需要替换当前路径
     *
     * @param string $url
     * @return boolean
     */
    protected function localeUrl(string $url):bool{

        if (strpos($url,'://')===false){
            return true;
        }else{
            return false;
        }


    }

    protected function compileUrl($base_url,$url){

        //判断是否有 “，“”
        $marks = "";
        if (substr($url,0,1)=="'" || substr($url,0,1)=='"'){
            $marks  = substr($url,0,1);
            $url = substr($url,1,strlen($url)-2);
        }

        
        $skip = array('http://','https://','data:image','/','#','javascript');
         // echo $v;
        $not_replace = false;
        foreach($skip as $k){
            if (substr($url,0,strlen($k))==$k){

                if ($k=='data:image'){
                  
                    $url = '"'. $url .'"';
                     
                }
            $not_replace =  true;
            }
        }

        if ($not_replace) return $url;

        $arr = explode('/',$url);
        $new_arr = array();
        //$new_sum = 0;
        $up_folder_number = 1;
        $up_lab = true;

        foreach($arr as $v){
            if ($v=='..' && $up_lab){
                $up_folder_number ++;
            }else{
                $up_lab = false;
                $new_arr[] = $v;
            }
        }
 


        if (substr($base_url,0,1)=='/') $base_url =  substr($base_url,1);

        $base_url_arr = explode('/',$base_url);
        $base_url_arr = array_slice($base_url_arr,0,count($base_url_arr)-$up_folder_number);
 
        return $marks.'/'.implode('/',array_merge($base_url_arr,$new_arr)).$marks;

    }

    public function export($content){
        
        $has = false;

        if (!$has){
            $reg ="/\n+\s*(export[\s]+default)\s?/";
            preg_match_all ($reg, $content, $match);

            if (isset($match[1]) && count($match[1])==1){
                $has = true;
                $content = preg_replace($reg,"\n  return ",$content,1);
            }
        }

        if (!$has){
            $reg ="/^(export[\s]+default)[\s]?/";
            
            preg_match_all ($reg, $content, $match);

            if (isset($match[1]) && count($match[1])==1){
                $has = true;
                $content = preg_replace($reg,"\n return ",$content,1);
            }
        }
        

        if (!$has){
            
            $reg ="/^(export)\s{1}/";
            //echo $content;
            preg_match_all ($reg, $content, $match);
            if (isset($match[1]) && count($match[1])==1){
                
                $has = true;
                $content = preg_replace($reg,"\n  return ",$content,1);
            }
        }


        if (!$has){
            
            $reg ="/\n+\s*(export)\s{1}/";
            //echo $content;
            preg_match_all ($reg, $content, $match);
            if (isset($match[1]) && count($match[1])==1){
                $has = true;
                $content = preg_replace($reg,"\n  return ",$content,1);
            }
        }
    
        //$this->useExport = $has;
        return $content;
    }

    public static function variable(){
        return false;
    }
}